package com.example.hrsystem.ui.user;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import java.util.List;
import androidx.lifecycle.LiveData;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import com.example.hrsystem.R;
import com.example.hrsystem.data.model.User;
import com.example.hrsystem.data.source.AppDatabase;

/**
 * 个人中心Fragment
 * 用于展示用户的个人信息
 */
public class ProfileFragment extends Fragment {

    private TextView userNameTextView;
    private TextView employeeIdTextView;
    private TextView departmentTextView;
    private TextView positionTextView;
    private TextView emailTextView;
    private TextView phoneNumberTextView;
    private TextView entryDateTextView;
    private Button logoutButton; // 退出登录按钮
    private Button editButton; // 编辑个人信息按钮
    private TextView userTypeTextView;
    private TextView statusTextView;
    private boolean isEditing = false; // 编辑状态标志
    
    // 编辑模式下的控件
    private EditText userNameEditText;
    private EditText departmentEditText;
    private EditText positionEditText;
    private EditText emailEditText;
    private EditText phoneNumberEditText;
    
    private AppDatabase database;
    private String currentEmployeeId; // 登录用户的员工ID

    public ProfileFragment() {
        // Required empty public constructor
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_profile, container, false);

        // 初始化数据库
        if (getActivity() != null) {
            database = AppDatabase.getDatabase(getActivity().getApplicationContext());
            
            // 获取登录用户信息
            SharedPreferences userPrefs = getActivity().getSharedPreferences("user_prefs", getActivity().MODE_PRIVATE);
            currentEmployeeId = userPrefs.getString("employee_id", "1001"); // 默认值仅用于开发测试
        }
        
        // 初始化UI组件
        initViews(view);

        // 加载用户信息
        loadUserInfo();

        // 设置退出登录按钮点击事件
        setupLogoutButton();

        return view;
    }

    /**
     * 初始化UI组件
     */
    private void initViews(View view) {
        // 显示模式的TextViews
        userNameTextView = view.findViewById(R.id.user_name_text_view);
        employeeIdTextView = view.findViewById(R.id.employee_id_text_view);
        departmentTextView = view.findViewById(R.id.department_text_view);
        positionTextView = view.findViewById(R.id.position_text_view);
        emailTextView = view.findViewById(R.id.email_text_view);
        phoneNumberTextView = view.findViewById(R.id.phone_number_text_view);
        entryDateTextView = view.findViewById(R.id.entry_date_text_view);
        userTypeTextView = view.findViewById(R.id.user_type_text_view);
        statusTextView = view.findViewById(R.id.status_text_view);
        logoutButton = view.findViewById(R.id.sign_out_button);
        
        // 尝试找到或创建编辑模式的EditTexts
        userNameEditText = findOrCreateEditText(view, R.id.user_name_text_view, "userNameEditText");
        departmentEditText = findOrCreateEditText(view, R.id.department_text_view, "departmentEditText");
        positionEditText = findOrCreateEditText(view, R.id.position_text_view, "positionEditText");
        emailEditText = findOrCreateEditText(view, R.id.email_text_view, "emailEditText");
        phoneNumberEditText = findOrCreateEditText(view, R.id.phone_number_text_view, "phoneNumberEditText");
        
        // 默认隐藏所有编辑框
        userNameEditText.setVisibility(View.GONE);
        departmentEditText.setVisibility(View.GONE);
        positionEditText.setVisibility(View.GONE);
        emailEditText.setVisibility(View.GONE);
        phoneNumberEditText.setVisibility(View.GONE);
        
        // 创建编辑按钮
        editButton = new Button(getContext());
        editButton.setText("编辑信息");
        editButton.setId(View.generateViewId()); // 动态生成ID
        
        // 将按钮添加到视图中
        ViewGroup parent = (ViewGroup) logoutButton.getParent();
        if (parent != null) {
            // 在退出按钮之前添加编辑按钮
            int index = parent.indexOfChild(logoutButton);
            if (index > 0) {
                parent.addView(editButton, index);
            } else {
                parent.addView(editButton);
            }
        }
        
        // 设置编辑按钮点击事件
        setupEditButton();
    }
    
    /**
     * 查找或创建EditText
     */
    private EditText findOrCreateEditText(View rootView, int textViewId, String editTextId) {
        ViewGroup parent = (ViewGroup) rootView.findViewById(textViewId).getParent();
        if (parent != null) {
            // 尝试找到现有的EditText
            for (int i = 0; i < parent.getChildCount(); i++) {
                View child = parent.getChildAt(i);
                if (child instanceof EditText && child.getTag() != null && editTextId.equals(child.getTag().toString())) {
                    return (EditText) child;
                }
            }
            
            // 创建新的EditText
            EditText editText = new EditText(getContext());
            editText.setLayoutParams(new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, 
                    ViewGroup.LayoutParams.WRAP_CONTENT));
            editText.setTag(editTextId);
            editText.setId(View.generateViewId());
            
            // 找到TextView的位置并在其后添加EditText
            TextView textView = parent.findViewById(textViewId);
            if (textView != null) {
                int index = parent.indexOfChild(textView);
                parent.addView(editText, index + 1);
            }
            
            return editText;
        }
        
        // 回退方案
        return new EditText(getContext());
    }

    /**
     * 加载用户信息
     * 从SharedPreferences中获取登录用户信息
     */
    private void loadUserInfo() {
        if (getActivity() != null && currentEmployeeId != null) {
            // 优先使用员工ID查询用户信息
            try {
                User user = getUserByEmployeeId(currentEmployeeId);
                if (user != null) {
                    // 回显用户信息
                    userNameTextView.setText(user.getName());
                    employeeIdTextView.setText(user.getEmployeeId());
                    departmentTextView.setText(user.getDepartment());
                    positionTextView.setText(user.getPosition());
                    emailTextView.setText(user.getEmail());
                    phoneNumberTextView.setText(user.getPhoneNumber());
                    entryDateTextView.setText(user.getEntryDate());
                    userTypeTextView.setText(user.getUserType());
                    statusTextView.setText(user.isActive() ? "在职" : "离职");
                    return;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        // 如果无法获取登录用户信息，尝试使用手机号查询
        if (getActivity() != null) {
            SharedPreferences preferences = getActivity().getSharedPreferences("user_prefs", getActivity().MODE_PRIVATE);
            String phoneNumber = preferences.getString("phone_number", "");
            
            if (!phoneNumber.isEmpty()) {
                User user = getUserByPhoneNumber(phoneNumber);
                if (user != null) {
                    // 回显用户信息
                    userNameTextView.setText(user.getName());
                    employeeIdTextView.setText(user.getEmployeeId());
                    departmentTextView.setText(user.getDepartment());
                    positionTextView.setText(user.getPosition());
                    emailTextView.setText(user.getEmail());
                    phoneNumberTextView.setText(user.getPhoneNumber());
                    entryDateTextView.setText(user.getEntryDate());
                    userTypeTextView.setText(user.getUserType());
                    statusTextView.setText(user.isActive() ? "在职" : "离职");
                    return;
                }
            }
        }
        
        // 如果仍然无法获取用户信息，使用默认的模拟数据
        User defaultUser = getSampleUser();
        if (defaultUser != null) {
            userNameTextView.setText(defaultUser.getName());
            employeeIdTextView.setText(defaultUser.getEmployeeId());
            departmentTextView.setText(defaultUser.getDepartment());
            positionTextView.setText(defaultUser.getPosition());
            emailTextView.setText(defaultUser.getEmail());
            phoneNumberTextView.setText(defaultUser.getPhoneNumber());
            entryDateTextView.setText(defaultUser.getEntryDate());
            userTypeTextView.setText(defaultUser.getUserType());
            statusTextView.setText(defaultUser.isActive() ? "在职" : "离职");
        }
    }
    
    /**
     * 根据员工ID获取用户信息
     * 由于UserDao没有同步版本，我们使用异步查询并等待结果
     */
    private User getUserByEmployeeId(String employeeId) {
        try {
            // 使用ExecutorService在后台执行查询
            ExecutorService executor = Executors.newSingleThreadExecutor();
            Future<User> future = executor.submit(() -> {
                LiveData<User> userLiveData = AppDatabase.getDatabase(requireContext()).userDao().getUserByEmployeeId(employeeId);
                // 由于LiveData在主线程中观察，我们直接使用SQLiteDatabase查询
                // 这里使用简单的查询替代
                List<User> allUsers = AppDatabase.getDatabase(requireContext()).userDao().getAllUsersDirect();
                for (User user : allUsers) {
                    if (employeeId.equals(user.getEmployeeId())) {
                        return user;
                    }
                }
                return null;
            });
            User user = future.get(2, TimeUnit.SECONDS); // 设置2秒超时
            executor.shutdown();
            return user;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    private User getUserByPhoneNumber(String phoneNumber) {
        // 通过Repository获取用户信息
        try {
            List<User> users = AppDatabase.getDatabase(requireContext()).userDao().getUsersByPhoneNumber(phoneNumber);
            if (users != null && !users.isEmpty()) {
                return users.get(0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 如果数据库查询失败，返回默认用户信息
        return getDefaultUser();
    }
    
    private User getDefaultUser() {
        User user = new User();
        user.setName("张三");
        user.setEmployeeId("1001");
        user.setDepartment("技术部");
        user.setPosition("Android开发工程师");
        user.setEmail("zhangsan@example.com");
        user.setPhoneNumber("13800138000");
        user.setEntryDate("2023-01-15");
        user.setUserType("普通员工");
        user.setActive(true);
        return user;
    }

    /**
     * 设置退出登录按钮点击事件
     */
    private void setupLogoutButton() {
        logoutButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 清除登录状态
                clearLoginState();
                // 跳转到登录页面
                navigateToLoginActivity();
            }
        });
    }

    /**
     * 清除登录状态
     */
    private void clearLoginState() {
        SharedPreferences preferences = getActivity().getSharedPreferences("user_prefs", getActivity().MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean("is_logged_in", false);
        editor.putString("phone_number", "");
        editor.apply();
    }

    /**
     * 设置编辑按钮点击事件
     */
    private void setupEditButton() {
        editButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isEditing) {
                    // 保存编辑的信息
                    saveUserInfo();
                } else {
                    // 进入编辑模式
                    startEditMode();
                }
            }
        });
    }
    
    /**
     * 进入编辑模式
     */
    private void startEditMode() {
        if (getActivity() != null) {
            Toast.makeText(getActivity(), "进入编辑模式，请修改个人信息", Toast.LENGTH_SHORT).show();
            
            // 更新按钮状态
            editButton.setText("保存信息");
            isEditing = true;
            
            // 隐藏显示模式的TextViews，显示编辑模式的EditTexts
            userNameTextView.setVisibility(View.GONE);
            departmentTextView.setVisibility(View.GONE);
            positionTextView.setVisibility(View.GONE);
            emailTextView.setVisibility(View.GONE);
            phoneNumberTextView.setVisibility(View.GONE);
            
            // 设置EditTexts的值并显示
            userNameEditText.setText(userNameTextView.getText().toString());
            departmentEditText.setText(departmentTextView.getText().toString());
            positionEditText.setText(positionTextView.getText().toString());
            emailEditText.setText(emailTextView.getText().toString());
            phoneNumberEditText.setText(phoneNumberTextView.getText().toString());
            
            userNameEditText.setVisibility(View.VISIBLE);
            departmentEditText.setVisibility(View.VISIBLE);
            positionEditText.setVisibility(View.VISIBLE);
            emailEditText.setVisibility(View.VISIBLE);
            phoneNumberEditText.setVisibility(View.VISIBLE);
        }
    }
    
    /**
     * 保存用户信息
     */
    private void saveUserInfo() {
        if (getActivity() != null) {
            // 获取用户输入的信息
            final String userName = userNameEditText.getText().toString().trim();
            final String department = departmentEditText.getText().toString().trim();
            final String position = positionEditText.getText().toString().trim();
            final String email = emailEditText.getText().toString().trim();
            final String phoneNumber = phoneNumberEditText.getText().toString().trim();
            
            // 简单验证
            if (userName.isEmpty()) {
                Toast.makeText(getActivity(), "姓名不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            
            // 保存到数据库
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        // 创建或更新用户对象
                        User user = new User();
                        user.setName(userName);
                        user.setEmployeeId(employeeIdTextView.getText().toString());
                        user.setDepartment(department);
                        user.setPosition(position);
                        user.setEmail(email);
                        user.setPhoneNumber(phoneNumber);
                        user.setEntryDate(entryDateTextView.getText().toString());
                        user.setUserType(userTypeTextView.getText().toString());
                        user.setActive(true);
                        
                        // 尝试更新数据库
                        if (database != null) {
                            try {
                                // 优先根据员工ID查询用户（这是最准确的方法）
                                // 使用直接查询方式
                                List<User> allUsers = database.userDao().getAllUsersDirect();
                                User existingUser = null;
                                for (User u : allUsers) {
                                    if (employeeIdTextView.getText().toString().equals(u.getEmployeeId())) {
                                        existingUser = u;
                                        break;
                                    }
                                }
                                
                                if (existingUser != null) {
                                    // 更新现有用户
                                    user.setUserId(existingUser.getUserId());
                                    database.userDao().update(user);
                                    
                                    // 确保currentEmployeeId被正确设置
                                    currentEmployeeId = existingUser.getEmployeeId();
                                } else {
                                    // 如果根据员工ID找不到，则尝试根据手机号查询
                                    List<User> users = database.userDao().getUsersByPhoneNumber(phoneNumber);
                                    if (users != null && !users.isEmpty()) {
                                        // 更新手机号对应的用户
                                        User phoneUser = users.get(0);
                                        user.setUserId(phoneUser.getUserId());
                                        database.userDao().update(user);
                                    } else {
                                        // 如果都找不到，则插入新用户
                                        database.userDao().insert(user);
                                    }
                                }
                            } catch (Exception e) {
                                // 数据库操作失败，记录日志但继续
                                e.printStackTrace();
                            }
                        }
                        
                        // 在主线程更新UI和SharedPreferences
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                // 更新TextViews显示新信息
                                userNameTextView.setText(userName);
                                departmentTextView.setText(department);
                                positionTextView.setText(position);
                                emailTextView.setText(email);
                                phoneNumberTextView.setText(phoneNumber);
                                
                                // 保存到SharedPreferences
                                SharedPreferences preferences = getActivity().getSharedPreferences("user_prefs", getActivity().MODE_PRIVATE);
                                SharedPreferences.Editor editor = preferences.edit();
                                editor.putString("user_name", userName);
                                editor.putString("phone_number", phoneNumber);
                                editor.putString("email", email);
                                editor.putString("department", department);
                                editor.putString("position", position);
                                editor.apply();
                                
                                Toast.makeText(getActivity(), "个人信息已更新", Toast.LENGTH_SHORT).show();
                                
                                // 恢复显示模式
                                userNameTextView.setVisibility(View.VISIBLE);
                                departmentTextView.setVisibility(View.VISIBLE);
                                positionTextView.setVisibility(View.VISIBLE);
                                emailTextView.setVisibility(View.VISIBLE);
                                phoneNumberTextView.setVisibility(View.VISIBLE);
                                
                                userNameEditText.setVisibility(View.GONE);
                                departmentEditText.setVisibility(View.GONE);
                                positionEditText.setVisibility(View.GONE);
                                emailEditText.setVisibility(View.GONE);
                                phoneNumberEditText.setVisibility(View.GONE);
                                
                                // 恢复按钮状态
                                editButton.setText("编辑信息");
                                isEditing = false;
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getActivity(), "保存失败，请重试", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }
            }).start();
        }
    }
    
    /**
     * 跳转到登录页面
     */
    private void navigateToLoginActivity() {
        // 跳转到登录页面而不是直接退出
        Intent intent = new Intent(getActivity(), LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        if (getActivity() != null) {
            getActivity().finish();
        }
    }

    /**
     * 获取示例用户信息
     */
    private User getSampleUser() {
        User user = new User();
        user.setName("张三");
        user.setEmployeeId("EMP001");
        user.setDepartment("技术部");
        user.setPosition("软件工程师");
        user.setEmail("zhangsan@example.com");
        user.setPhoneNumber("13800138000");
        user.setEntryDate("2022-01-01");
        user.setUserType("普通员工");
        user.setActive(true);
        return user;
    }
}